package com.application.goods.service;

import com.excellent.common.utils.ThreadUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.File;
import java.io.PrintWriter;
import java.util.Map;

/**
 * 【商品页面静态化：该 Service 专门用来生成 Html 页面】
 * @author Xxacker
 */
@Service
public class GoodsHtmlService {

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private TemplateEngine templateEngine;    //注入模板引擎，用来生成静态页面

    @Value("${item-html.path}")
    private String HTML_PATH;

    private static final Logger LOGGER = LoggerFactory.getLogger(GoodsHtmlService.class);

    /**
     * 创建html页面
     * 该方法会被 GoodsController 调用，第一次访问没有静态方法
     * @param spuId
     * @throws Exception
     */
    public void createHtml(Long spuId) {

        PrintWriter writer = null;
        try {
            // 获取页面数据
            Map<String, Object> spuMap = this.goodsService.loadModel(spuId);

            // 创建thymeleaf上下文对象
            Context context = new Context();
            // 把数据放入上下文对象
            context.setVariables(spuMap);

            // 创建输出流：输出流的位置在 nginx 的安装位置下
//            File file = new File(HTML_PATH + spuId + ".html");
            File file = new File("/usr/local/nginx/html/item/" + spuId + ".html");

            writer = new PrintWriter(file);

            // 执行生成页面静态化方法（模板名称，运行上下文，io流）
            templateEngine.process("item", context, writer);
        } catch (Exception e) {
            LOGGER.error("页面静态化出错：{}，"+ e, spuId);
        } finally {
            //最后将流进行释放
            if (writer != null) {
                writer.close();
            }
        }
    }

    /**
     * 新建线程处理页面静态化
     * @param spuId
     */
    public void asyncExcute(Long spuId) {
        // 为了防止生成静态页面时发生阻塞，使用线程池的方式
        ThreadUtils.execute(()->createHtml(spuId));

       /*ThreadUtils.execute(new Runnable() {
           @Override
           public void run() {
               createHtml(spuId);
           }
       });*/
    }

    public void deleteHtml(Long id) {
//        File file = new File(HTML_PATH, id + ".html");
        File file = new File("/usr/local/nginx/html/item/", id + ".html");
        file.deleteOnExit();
    }
}
